package com.nice.nice201110.service;

import com.nice.nice201110.entity.*;
import com.nice.nice201110.mapper.*;
import com.nice.nice201110.utils.NiceEnum;
import com.nice.nice201110.utils.NiceTableEnum;
import com.nice.nice201110.vo.BaseVo;
import com.nice.nice201110.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class TdeliveryService {

    //出库Dao对象
    @Autowired
    TDeliveryMapper tDeliveryMapper;

    //获取资产的Dao
    @Autowired
    TBaseCapitalMapper tBaseCapitalMapper;

    //获取药品的Dao
    @Autowired
    TBasePictureMapper tBasePictureMapper;

    //获取资产的Dao
    @Autowired
    TDeliveryDelMapper tDeliveryDelMapper;

    @Autowired
    TLogMapper tLogMapper;

    @Autowired
    private PlatformTransactionManager ransactionManager;

    private TLog tLog = new TLog();

    /** 查询数据 */
    public List<TDelivery> getList(BaseVo baseVo){
        return tDeliveryMapper.selectByPrimaryKeys(baseVo);
    }
    /** 单一查询  */
    public TDelivery getOne(UserVo userVo, Integer id){
        TDelivery tDelivery = tDeliveryMapper.selectByPrimaryKey(id);
        if(tDelivery!=null){
            tLog.setDate(new Date());
            tLog.setType(3);  //操作类型（新增0，修改1，删除2,查询3）
            tLog.setDocid(tDelivery.getId());
            tLog.setUsername(userVo.getName());
            tLog.setUserid(Integer.valueOf(userVo.getId()));
            tLog.setTtable(NiceTableEnum.form_delivery);
            tLog.setRemark("查看出库信息:"+tDelivery.toString());
            tLogMapper.insertSelective(tLog);
        }
        return tDelivery;
    }
    /** 出库操作 */
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public Boolean insertttDelivery(UserVo userVo,TDelivery tDelivery){
        try {
            int num = tDeliveryMapper.insertSelective(tDelivery);
            if(num>0){
                tLog.setDate(new Date());
                tLog.setType(0);  //操作类型（新增0，修改1，删除2）
                tLog.setDocid(tDelivery.getId());
                tLog.setUsername(userVo.getName());
                tLog.setUserid(Integer.valueOf(userVo.getId()));
                tLog.setTtable(NiceTableEnum.form_delivery);
                tLog.setRemark("新增出库信息:"+tDelivery.toString());
                tLogMapper.insertSelective(tLog);
            }else{
                return false;
            }
            //根据出库数量更新资产
            BigDecimal StorageQuantity = tDelivery.getNumber();  //获取出库数量
            int CapitalId = tDelivery.getName();  //资产id 药品id
            String ttype = tDelivery.getType();  //类型（资产0 /药品1）
            String Informationids = tDelivery.getInformationids();  //用药（基本信息IDS）
            Integer docid = tDelivery.getId(); // 获取出库id
            if("0".equals(ttype)){
                TBaseCapital tBaseCapital = tBaseCapitalMapper.selectByPrimaryKey(CapitalId);
                if(tBaseCapital!=null){
                    Integer StorageQuantityInt = StorageQuantity.intValue();  // 出库数量
                    Integer dNumber = tBaseCapital.getNumber();  //获取资产数量
                    Integer allNumber = dNumber - StorageQuantityInt;
                    tBaseCapital.setNumber(allNumber);
                    Integer isSertNum = tBaseCapitalMapper.updateByPrimaryKeySelective(tBaseCapital);
                    if(isSertNum<0){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return false;
                    }
                    String CapitalName = tBaseCapital.getName();
                    tLog.setDate(new Date());
                    tLog.setType(1);  //操作类型（新增0，修改1，删除2）
                    tLog.setDocid(tBaseCapital.getId());
                    tLog.setUsername(userVo.getName());
                    tLog.setUserid(Integer.valueOf(userVo.getId()));
                    tLog.setTtable(NiceTableEnum.form_base_capital);
                    tLog.setRemark("系统自动减少["+CapitalName+"]资产:"+StorageQuantity.toString());
                    tLogMapper.insertSelective(tLog);
                }else{
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
                if(Informationids!=null&&Informationids.trim().length()>0){
                    String InformationidArr [] = Informationids.split(",");
                    Integer InformationSize = InformationidArr.length;
                    Double StorageQuantityDouble = StorageQuantity.doubleValue();  // 出库数量
                    Double InformationNum = StorageQuantityDouble/InformationSize;
                    BigDecimal BInformationNum = BigDecimal.valueOf(InformationNum);
                    BigDecimal Price = tBaseCapital.getPrice();  //获取资产单价
                    BigDecimal pPrice = BInformationNum.multiply(Price);  //单价＊数量
                    for(String Informationid:InformationidArr){
                        TDeliveryDel tDeliveryDel = new TDeliveryDel();
                        tDeliveryDel.setType(NiceEnum.del_chuku);
                        tDeliveryDel.setAmountSpent(pPrice);  // 花费金额
                        tDeliveryDel.setDeliveryTime(new Date());
                        tDeliveryDel.setInformationid(Informationid);//基本信息id
                        tDeliveryDel.setParentid(docid);   //父类id
                        tDeliveryDel.setName(CapitalId);   // 资产id
                        tDeliveryDel.setNumber(BInformationNum);  //数量
                        int tDeliveryDelInsertNum = tDeliveryDelMapper.insertSelective(tDeliveryDel);
                        if(tDeliveryDelInsertNum<=0){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return false;
                        }
                    }
                }
            }else if("1".equals(ttype)){
                TBasePicture tBasePicture = tBasePictureMapper.selectByPrimaryKey(CapitalId);
                if(tBasePicture!=null){
                    BigDecimal dNumber = tBasePicture.getNumber();
                    BigDecimal allNumber = dNumber.subtract(StorageQuantity);
                    tBasePicture.setNumber(allNumber);
                    Integer isSertNum = tBasePictureMapper.insertSelective(tBasePicture);
                    if(isSertNum<0){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return false;
                    }
                    String PictureName = tBasePicture.getName();
                    tLog.setDate(new Date());
                    tLog.setType(1);  //操作类型（新增0，修改1，删除2）
                    tLog.setDocid(tBasePicture.getId());
                    tLog.setUsername(userVo.getName());
                    tLog.setUserid(Integer.valueOf(userVo.getId()));
                    tLog.setTtable(NiceTableEnum.form_base_picture);
                    tLog.setRemark("系统自动减少["+PictureName+"]药品:"+StorageQuantity.toString());
                    tLogMapper.insertSelective(tLog);
                }else{
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
                if(Informationids!=null&&Informationids.trim().length()>0){
                    String InformationidArr [] = Informationids.split(",");
                    Integer InformationSize = InformationidArr.length;
                    Double StorageQuantityDouble = StorageQuantity.doubleValue();  // 出库数量
                    Double InformationNum = StorageQuantityDouble/InformationSize;
                    BigDecimal BInformationNum = BigDecimal.valueOf(InformationNum);
                    BigDecimal Price = tBasePicture.getPrice();  //获取药品单价
                    BigDecimal pPrice = BInformationNum.multiply(Price);  //单价＊数量
                    for(String Informationid:InformationidArr){
                        TDeliveryDel tDeliveryDel = new TDeliveryDel();
                        tDeliveryDel.setType(NiceEnum.del_chuku);
                        tDeliveryDel.setAmountSpent(pPrice);  // 花费金额
                        tDeliveryDel.setDeliveryTime(new Date());
                        tDeliveryDel.setInformationid(Informationid);//基本信息id
                        tDeliveryDel.setParentid(docid);   //父类id
                        tDeliveryDel.setName(CapitalId);   // 资产id
                        tDeliveryDel.setNumber(BInformationNum);  //数量
                        int tDeliveryDelInsertNum = tDeliveryDelMapper.insertSelective(tDeliveryDel);
                        if(tDeliveryDelInsertNum<=0){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return false;
                        }
                    }
                }
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }
    /** 出库操作失误删除 */
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public Boolean deletetDelivery(UserVo userVo,Integer id){
        try {
            TDelivery tDelivery = tDeliveryMapper.selectByPrimaryKey(id);
            if(tDelivery==null){
                return false;
            }
            int num = tDeliveryMapper.deleteByPrimaryKey(id);
            if(num>0){
                tLog.setDate(new Date());
                tLog.setType(2);  //操作类型（新增0，修改1，删除2）
                tLog.setDocid(id);
                tLog.setUsername(userVo.getName());
                tLog.setUserid(Integer.valueOf(userVo.getId()));
                tLog.setTtable(NiceTableEnum.form_delivery);
                tLog.setRemark("删除出库信息:"+tDelivery.toString());
                tLogMapper.insertSelective(tLog);
            }else{
                return false;
            }
            //根据出库数量更新资产
            BigDecimal StorageQuantity = tDelivery.getNumber();  //获取出库数量
            int CapitalId = tDelivery.getName();  //资产id 药品id
            String ttype = tDelivery.getType();  //类型（资产0 /药品1）
            String Informationids = tDelivery.getInformationids();  //用药（基本信息IDS）
            Integer docid = tDelivery.getId(); // 获取出库id
            if("0".equals(ttype)){
                TBaseCapital tBaseCapital = tBaseCapitalMapper.selectByPrimaryKey(CapitalId);
                if(tBaseCapital!=null){
                    Integer StorageQuantityInt = StorageQuantity.intValue();  // 出库数量
                    Integer dNumber = tBaseCapital.getNumber();  //获取资产数量
                    Integer allNumber = dNumber + StorageQuantityInt;
                    tBaseCapital.setNumber(allNumber);
                    Integer isSertNum = tBaseCapitalMapper.updateByPrimaryKeySelective(tBaseCapital);
                    if(isSertNum<0){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return false;
                    }
                    String CapitalName = tBaseCapital.getName();
                    tLog.setDate(new Date());
                    tLog.setType(1);  //操作类型（新增0，修改1，删除2）
                    tLog.setDocid(tBaseCapital.getId());
                    tLog.setUsername(userVo.getName());
                    tLog.setUserid(Integer.valueOf(userVo.getId()));
                    tLog.setTtable(NiceTableEnum.form_base_capital);
                    tLog.setRemark("系统自动回滚["+CapitalName+"]资产:"+StorageQuantity.toString());
                    tLogMapper.insertSelective(tLog);
                }else{
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
                int tDeliveryDelInsertNum = tDeliveryDelMapper.deleteByParentId(id,NiceEnum.del_chuku);
                if(tDeliveryDelInsertNum<=0){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
            }else if("1".equals(ttype)){
                TBasePicture tBasePicture = tBasePictureMapper.selectByPrimaryKey(CapitalId);
                if(tBasePicture!=null){
                    BigDecimal dNumber = tBasePicture.getNumber();
                    BigDecimal allNumber = dNumber.add(StorageQuantity);
                    tBasePicture.setNumber(allNumber);
                    Integer isSertNum = tBasePictureMapper.insertSelective(tBasePicture);
                    if(isSertNum<0){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return false;
                    }
                    String PictureName = tBasePicture.getName();
                    tLog.setDate(new Date());
                    tLog.setType(1);  //操作类型（新增0，修改1，删除2）
                    tLog.setDocid(tBasePicture.getId());
                    tLog.setUsername(userVo.getName());
                    tLog.setUserid(Integer.valueOf(userVo.getId()));
                    tLog.setTtable(NiceTableEnum.form_base_picture);
                    tLog.setRemark("系统自动回滚["+PictureName+"]药品:"+StorageQuantity.toString());
                    tLogMapper.insertSelective(tLog);
                }else{
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
                int tDeliveryDelInsertNum = tDeliveryDelMapper.deleteByParentId(id,NiceEnum.del_chuku);
                if(tDeliveryDelInsertNum<=0){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }
}
